package routers

import (
	"context"
	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/common/utils"
	"github.com/cloudwego/hertz/pkg/route"
	"hertz/api"
	"hertz/pojo"
	myUtils "hertz/utils"
)

func loadMessage(h *route.RouterGroup) {
	message := h.Group("/message")
	{
		message.POST("/action/", addMessage)
		message.GET("/chat/", getMessageList)
	}
}

func addMessage(c context.Context, ctx *app.RequestContext) {
	messageAction := myUtils.GetParamMessage(ctx)

	// 鉴权
	user, err := userProvider.Authenticate(c, &api.Token{
		Token:     messageAction.Token,
		Operation: "SEND_MESSAGE",
	})
	if err != nil {
		FAIL(ctx, err)
		return
	}

	_, err = messageProvider.Add(c, &api.Message{
		UserAId: user.GetId(),
		UserBId: transInt64(messageAction.UserId),
		Content: messageAction.Content,
	})
	if err != nil {
		FAIL(ctx, err)
		return
	}

	OK(ctx, nil)
}

func getMessageList(c context.Context, ctx *app.RequestContext) {
	messageAction := myUtils.GetParamMessage(ctx)

	// 鉴权
	user, err := userProvider.Authenticate(c, &api.Token{
		Token:     messageAction.Token,
		Operation: "GET_MESSAGE_LIST",
	})
	if err != nil {
		FAIL(ctx, err)
		return
	}

	messageList, err := messageProvider.Find(c, &api.Message{
		UserAId: user.GetId(),
		UserBId: transInt64(messageAction.UserId),
	})
	if err != nil {
		FAIL(ctx, err)
		return
	}

	var list []pojo.Message
	for _, value := range messageList.GetList() {
		list = append(list, transMessage(user, value))
	}
	OK(ctx, utils.H{"message_list": list})
}
